/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yyx.demo.lock;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

class ZKLockProtocolSupport {

    private static final Logger LOG = LoggerFactory.getLogger(ZKLockProtocolSupport.class);


    //加锁尝试次数
    private static final int RETRY_COUNT = 10;

    protected final ZooKeeper zookeeper;
    private AtomicBoolean closed = new AtomicBoolean(false);
    private long retryDelay = 500L;
    private List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;

    public ZKLockProtocolSupport(ZooKeeper zookeeper) {
        this.zookeeper = zookeeper;
    }

    public void close() {
        //状态改为已关闭
        if (closed.compareAndSet(false, true)) {
            //预处理，实现自定义操作
            doClose();
        }
    }

    public ZooKeeper getZookeeper() {
        return zookeeper;
    }

    public long getRetryDelay() {
        return retryDelay;
    }

    public void setRetryDelay(long retryDelay) {
        this.retryDelay = retryDelay;
    }

    protected void doClose() {
    }
    /**
     * 节点加锁操作
     * @param operation
     * @return
     * @throws KeeperException
     * @throws InterruptedException
     */
    protected Object retryOperation(ZKOperation operation)
        throws KeeperException, InterruptedException {
        KeeperException exception = null;


        for (int i = 0; i < RETRY_COUNT; i++) {
            try {
                return operation.execute();
            } catch (KeeperException.SessionExpiredException e) {
                LOG.warn("Session expired {}. Reconnecting...", zookeeper, e);
                throw e;

                //连接丢失,延迟重试
            } catch (KeeperException.ConnectionLossException e) {
                if (exception == null) {
                    exception = e;
                }
                LOG.debug("Attempt {} failed with connection loss. Reconnecting...", i);
                retryDelay(i);
            }
        }

        throw exception;
    }

    /**
     * 确保改节点路径，无数据，临时节点
     */
    protected void ensurePathExists(String path) {
        ensureExists(path, null, CreateMode.PERSISTENT);
    }

    protected void ensureExists(
        final String path,
        final byte[] data,
        final CreateMode flags) {
        try {
            retryOperation(() -> {
                Stat stat = zookeeper.exists(path, false);
                LOG.debug("111");
                if (stat != null) {
                    return true;
                }
                zookeeper.create(path, data, acl, flags);
                return true;
            });
        } catch (KeeperException | InterruptedException e) {
            LOG.warn("Unexpected exception", e);
        }
    }


    protected boolean isClosed() {
        return closed.get();
    }


    //延迟重试
    protected void retryDelay(int attemptCount) {
        if (attemptCount > 0) {
            try {
                Thread.sleep(attemptCount * retryDelay);
            } catch (InterruptedException e) {
                LOG.warn("Failed to sleep.", e);
            }
        }
    }

}
